#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
触发器管理页面模块
"""

import logging
from PyQt6.QtWidgets import (
    QWidget, QVBoxLayout, QHBoxLayout, QLabel, QPushButton,
    QTabWidget, QFrame, QGridLayout, QLineEdit, QComboBox,
    QCheckBox, QSpinBox, QFileDialog, QMessageBox, QListWidget,
    QListWidgetItem, QTableWidget, QTableWidgetItem, QHeaderView,
    QDialog, QFormLayout, QDialogButtonBox, QStackedWidget,
    QMenu
)
from PyQt6.QtCore import Qt, QSize
from PyQt6.QtGui import QIcon, QAction, QColor


class TriggerDialog(QDialog):
    """触发器编辑对话框"""
    
    def __init__(self, trigger_type, trigger_data=None, parent=None):
        super().__init__(parent)
        self.trigger_type = trigger_type
        self.trigger_data = trigger_data or {}
        self.setWindowTitle(f"编辑{self._get_type_name()}触发器")
        self.resize(500, 400)
        self._setup_ui()
    
    def _get_type_name(self):
        """获取触发器类型名称"""
        type_names = {
            "file": "文件",
            "webhook": "Webhook",
            "email": "邮件",
            "schedule": "定时"
        }
        return type_names.get(self.trigger_type, "未知")
    
    def _setup_ui(self):
        """设置UI"""
        layout = QVBoxLayout(self)
        
        # 通用表单
        form_layout = QFormLayout()
        
        # 触发器名称
        self.name_edit = QLineEdit(self.trigger_data.get("name", ""))
        form_layout.addRow("触发器名称:", self.name_edit)
        
        # 触发器描述
        self.description_edit = QLineEdit(self.trigger_data.get("description", ""))
        form_layout.addRow("描述:", self.description_edit)
        
        # 启用状态
        self.enabled_checkbox = QCheckBox("启用")
        self.enabled_checkbox.setChecked(self.trigger_data.get("enabled", True))
        form_layout.addRow("", self.enabled_checkbox)
        
        layout.addLayout(form_layout)
        
        # 特定类型的配置
        type_config_frame = QFrame()
        type_config_frame.setFrameShape(QFrame.Shape.StyledPanel)
        type_config_layout = QVBoxLayout(type_config_frame)
        
        type_label = QLabel(f"{self._get_type_name()}触发器配置")
        type_label.setStyleSheet("font-weight: bold;")
        type_config_layout.addWidget(type_label)
        
        # 根据不同类型添加不同的配置项
        if self.trigger_type == "file":
            self._setup_file_config(type_config_layout)
        elif self.trigger_type == "webhook":
            self._setup_webhook_config(type_config_layout)
        elif self.trigger_type == "email":
            self._setup_email_config(type_config_layout)
        elif self.trigger_type == "schedule":
            self._setup_schedule_config(type_config_layout)
        
        layout.addWidget(type_config_frame)
        
        # 脚本选择
        script_label = QLabel("执行脚本:")
        layout.addWidget(script_label)
        
        self.script_combo = QComboBox()
        # 从脚本管理页面获取脚本列表
        scripts = self.parent().scripts_page.get_script_names() if hasattr(self.parent(), "scripts_page") else ["网页爬虫示例", "桌面自动化示例", "数据处理示例", "报表生成示例"]
        self.script_combo.addItems(scripts)
        current_script = self.trigger_data.get("script", "")
        if current_script:
            self.script_combo.setCurrentText(current_script)
        layout.addWidget(self.script_combo)
        
        # 按钮
        button_box = QDialogButtonBox(
            QDialogButtonBox.StandardButton.Save | QDialogButtonBox.StandardButton.Cancel
        )
        button_box.accepted.connect(self.accept)
        button_box.rejected.connect(self.reject)
        layout.addWidget(button_box)
    
    def _setup_file_config(self, layout):
        """设置文件触发器配置"""
        # 监控目录
        dir_layout = QHBoxLayout()
        dir_layout.addWidget(QLabel("监控目录:"))
        
        self.dir_edit = QLineEdit(self.trigger_data.get("directory", ""))
        dir_layout.addWidget(self.dir_edit)
        
        browse_btn = QPushButton("浏览...")
        browse_btn.clicked.connect(self._browse_directory)
        dir_layout.addWidget(browse_btn)
        
        layout.addLayout(dir_layout)
        
        # 文件模式
        self.pattern_edit = QLineEdit(self.trigger_data.get("pattern", "*.txt"))
        layout.addWidget(QLabel("文件模式 (如 *.txt):"))
        layout.addWidget(self.pattern_edit)
        
        # 监控选项
        self.recursive_checkbox = QCheckBox("包含子目录")
        self.recursive_checkbox.setChecked(self.trigger_data.get("recursive", False))
        layout.addWidget(self.recursive_checkbox)
        
        events_layout = QHBoxLayout()
        events_layout.addWidget(QLabel("监控事件:"))
        
        self.created_checkbox = QCheckBox("创建")
        self.created_checkbox.setChecked("created" in self.trigger_data.get("events", ["created"]))
        events_layout.addWidget(self.created_checkbox)
        
        self.modified_checkbox = QCheckBox("修改")
        self.modified_checkbox.setChecked("modified" in self.trigger_data.get("events", ["created"]))
        events_layout.addWidget(self.modified_checkbox)
        
        self.deleted_checkbox = QCheckBox("删除")
        self.deleted_checkbox.setChecked("deleted" in self.trigger_data.get("events", ["created"]))
        events_layout.addWidget(self.deleted_checkbox)
        
        layout.addLayout(events_layout)
    
    def _setup_webhook_config(self, layout):
        """设置Webhook触发器配置"""
        # 端口
        port_layout = QHBoxLayout()
        port_layout.addWidget(QLabel("监听端口:"))
        
        self.port_spinbox = QSpinBox()
        self.port_spinbox.setRange(1000, 65535)
        self.port_spinbox.setValue(self.trigger_data.get("port", 8000))
        port_layout.addWidget(self.port_spinbox)
        
        layout.addLayout(port_layout)
        
        # 路径
        path_layout = QHBoxLayout()
        path_layout.addWidget(QLabel("路径:"))
        
        self.path_edit = QLineEdit(self.trigger_data.get("path", "/webhook"))
        path_layout.addWidget(self.path_edit)
        
        layout.addLayout(path_layout)
        
        # 方法
        method_layout = QHBoxLayout()
        method_layout.addWidget(QLabel("HTTP方法:"))
        
        self.method_combo = QComboBox()
        self.method_combo.addItems(["POST", "GET", "PUT", "DELETE"])
        current_method = self.trigger_data.get("method", "POST")
        self.method_combo.setCurrentText(current_method)
        method_layout.addWidget(self.method_combo)
        
        layout.addLayout(method_layout)
        
        # 安全选项
        self.auth_checkbox = QCheckBox("需要认证")
        self.auth_checkbox.setChecked(self.trigger_data.get("auth_required", False))
        layout.addWidget(self.auth_checkbox)
    
    def _setup_email_config(self, layout):
        """设置邮件触发器配置"""
        # 邮箱服务器
        server_layout = QHBoxLayout()
        server_layout.addWidget(QLabel("IMAP服务器:"))
        
        self.server_edit = QLineEdit(self.trigger_data.get("server", ""))
        server_layout.addWidget(self.server_edit)
        
        layout.addLayout(server_layout)
        
        # 端口
        port_layout = QHBoxLayout()
        port_layout.addWidget(QLabel("端口:"))
        
        self.email_port_spinbox = QSpinBox()
        self.email_port_spinbox.setRange(1, 65535)
        self.email_port_spinbox.setValue(self.trigger_data.get("port", 993))
        port_layout.addWidget(self.email_port_spinbox)
        
        layout.addLayout(port_layout)
        
        # 用户名
        username_layout = QHBoxLayout()
        username_layout.addWidget(QLabel("用户名:"))
        
        self.username_edit = QLineEdit(self.trigger_data.get("username", ""))
        username_layout.addWidget(self.username_edit)
        
        layout.addLayout(username_layout)
        
        # 密码
        password_layout = QHBoxLayout()
        password_layout.addWidget(QLabel("密码:"))
        
        self.password_edit = QLineEdit(self.trigger_data.get("password", ""))
        self.password_edit.setEchoMode(QLineEdit.EchoMode.Password)
        password_layout.addWidget(self.password_edit)
        
        layout.addLayout(password_layout)
        
        # 检查间隔
        interval_layout = QHBoxLayout()
        interval_layout.addWidget(QLabel("检查间隔(秒):"))
        
        self.interval_spinbox = QSpinBox()
        self.interval_spinbox.setRange(60, 3600)
        self.interval_spinbox.setValue(self.trigger_data.get("check_interval", 300))
        interval_layout.addWidget(self.interval_spinbox)
        
        layout.addLayout(interval_layout)
        
        # 过滤条件
        self.subject_filter_edit = QLineEdit(self.trigger_data.get("subject_filter", ""))
        layout.addWidget(QLabel("主题过滤(正则表达式):"))
        layout.addWidget(self.subject_filter_edit)
        
        self.sender_filter_edit = QLineEdit(self.trigger_data.get("sender_filter", ""))
        layout.addWidget(QLabel("发件人过滤(正则表达式):"))
        layout.addWidget(self.sender_filter_edit)
    
    def _setup_schedule_config(self, layout):
        """设置定时触发器配置"""
        # 定时类型
        type_layout = QHBoxLayout()
        type_layout.addWidget(QLabel("定时类型:"))
        
        self.schedule_type_combo = QComboBox()
        self.schedule_type_combo.addItems(["间隔", "每天", "每周", "每月", "Cron表达式"])
        current_type = self.trigger_data.get("schedule_type", "间隔")
        self.schedule_type_combo.setCurrentText(current_type)
        self.schedule_type_combo.currentTextChanged.connect(self._on_schedule_type_changed)
        type_layout.addWidget(self.schedule_type_combo)
        
        layout.addLayout(type_layout)
        
        # 定时配置堆栈
        self.schedule_stack = QStackedWidget()
        
        # 间隔配置
        interval_widget = QWidget()
        interval_layout = QHBoxLayout(interval_widget)
        interval_layout.addWidget(QLabel("间隔(秒):"))
        
        self.interval_schedule_spinbox = QSpinBox()
        self.interval_schedule_spinbox.setRange(1, 86400)
        self.interval_schedule_spinbox.setValue(self.trigger_data.get("interval", 3600))
        interval_layout.addWidget(self.interval_schedule_spinbox)
        
        interval_layout.addStretch()
        self.schedule_stack.addWidget(interval_widget)
        
        # 每天配置
        daily_widget = QWidget()
        daily_layout = QHBoxLayout(daily_widget)
        daily_layout.addWidget(QLabel("时间:"))
        
        self.daily_hour_spinbox = QSpinBox()
        self.daily_hour_spinbox.setRange(0, 23)
        self.daily_hour_spinbox.setValue(self.trigger_data.get("hour", 8))
        daily_layout.addWidget(self.daily_hour_spinbox)
        
        daily_layout.addWidget(QLabel(":"))
        
        self.daily_minute_spinbox = QSpinBox()
        self.daily_minute_spinbox.setRange(0, 59)
        self.daily_minute_spinbox.setValue(self.trigger_data.get("minute", 0))
        daily_layout.addWidget(self.daily_minute_spinbox)
        
        daily_layout.addStretch()
        self.schedule_stack.addWidget(daily_widget)
        
        # 每周配置
        weekly_widget = QWidget()
        weekly_layout = QVBoxLayout(weekly_widget)
        
        day_layout = QHBoxLayout()
        day_layout.addWidget(QLabel("星期:"))
        
        self.day_combo = QComboBox()
        self.day_combo.addItems(["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"])
        current_day = self.trigger_data.get("day", "星期一")
        self.day_combo.setCurrentText(current_day)
        day_layout.addWidget(self.day_combo)
        
        weekly_layout.addLayout(day_layout)
        
        time_layout = QHBoxLayout()
        time_layout.addWidget(QLabel("时间:"))
        
        self.weekly_hour_spinbox = QSpinBox()
        self.weekly_hour_spinbox.setRange(0, 23)
        self.weekly_hour_spinbox.setValue(self.trigger_data.get("hour", 8))
        time_layout.addWidget(self.weekly_hour_spinbox)
        
        time_layout.addWidget(QLabel(":"))
        
        self.weekly_minute_spinbox = QSpinBox()
        self.weekly_minute_spinbox.setRange(0, 59)
        self.weekly_minute_spinbox.setValue(self.trigger_data.get("minute", 0))
        time_layout.addWidget(self.weekly_minute_spinbox)
        
        weekly_layout.addLayout(time_layout)
        self.schedule_stack.addWidget(weekly_widget)
        
        # 每月配置
        monthly_widget = QWidget()
        monthly_layout = QVBoxLayout(monthly_widget)
        
        day_of_month_layout = QHBoxLayout()
        day_of_month_layout.addWidget(QLabel("日期:"))
        
        self.day_of_month_spinbox = QSpinBox()
        self.day_of_month_spinbox.setRange(1, 31)
        self.day_of_month_spinbox.setValue(self.trigger_data.get("day_of_month", 1))
        day_of_month_layout.addWidget(self.day_of_month_spinbox)
        
        monthly_layout.addLayout(day_of_month_layout)
        
        monthly_time_layout = QHBoxLayout()
        monthly_time_layout.addWidget(QLabel("时间:"))
        
        self.monthly_hour_spinbox = QSpinBox()
        self.monthly_hour_spinbox.setRange(0, 23)
        self.monthly_hour_spinbox.setValue(self.trigger_data.get("hour", 8))
        monthly_time_layout.addWidget(self.monthly_hour_spinbox)
        
        monthly_time_layout.addWidget(QLabel(":"))
        
        self.monthly_minute_spinbox = QSpinBox()
        self.monthly_minute_spinbox.setRange(0, 59)
        self.monthly_minute_spinbox.setValue(self.trigger_data.get("minute", 0))
        monthly_time_layout.addWidget(self.monthly_minute_spinbox)
        
        monthly_layout.addLayout(monthly_time_layout)
        self.schedule_stack.addWidget(monthly_widget)
        
        # Cron表达式配置
        cron_widget = QWidget()
        cron_layout = QVBoxLayout(cron_widget)
        
        cron_layout.addWidget(QLabel("Cron表达式:"))
        
        self.cron_edit = QLineEdit(self.trigger_data.get("cron", "0 0 * * *"))
        self.cron_edit.setPlaceholderText("分 时 日 月 周 (例如: 0 8 * * 1-5)")
        cron_layout.addWidget(self.cron_edit)
        
        cron_help = QLabel("格式: 分钟 小时 日期 月份 星期")
        cron_help.setStyleSheet("color: gray; font-size: 12px;")
        cron_layout.addWidget(cron_help)
        
        self.schedule_stack.addWidget(cron_widget)
        
        layout.addWidget(self.schedule_stack)
        
        # 设置当前显示的配置页
        schedule_type_index = {"间隔": 0, "每天": 1, "每周": 2, "每月": 3, "Cron表达式": 4}
        self.schedule_stack.setCurrentIndex(schedule_type_index.get(current_type, 0))
    
    def _on_schedule_type_changed(self, text):
        """定时类型改变事件"""
        schedule_type_index = {"间隔": 0, "每天": 1, "每周": 2, "每月": 3, "Cron表达式": 4}
        self.schedule_stack.setCurrentIndex(schedule_type_index.get(text, 0))
    
    def _browse_directory(self):
        """浏览目录"""
        directory = QFileDialog.getExistingDirectory(self, "选择监控目录")
        if directory:
            self.dir_edit.setText(directory)
    
    def get_trigger_data(self):
        """获取触发器数据"""
        data = {
            "name": self.name_edit.text(),
            "description": self.description_edit.text(),
            "enabled": self.enabled_checkbox.isChecked(),
            "type": self.trigger_type,
            "script": self.script_combo.currentText()
        }
        
        # 根据不同类型获取特定配置
        if self.trigger_type == "file":
            events = []
            if self.created_checkbox.isChecked():
                events.append("created")
            if self.modified_checkbox.isChecked():
                events.append("modified")
            if self.deleted_checkbox.isChecked():
                events.append("deleted")
            
            data.update({
                "directory": self.dir_edit.text(),
                "pattern": self.pattern_edit.text(),
                "recursive": self.recursive_checkbox.isChecked(),
                "events": events
            })
        
        elif self.trigger_type == "webhook":
            data.update({
                "port": self.port_spinbox.value(),
                "path": self.path_edit.text(),
                "method": self.method_combo.currentText(),
                "auth_required": self.auth_checkbox.isChecked()
            })
        
        elif self.trigger_type == "email":
            data.update({
                "server": self.server_edit.text(),
                "port": self.email_port_spinbox.value(),
                "username": self.username_edit.text(),
                "password": self.password_edit.text(),
                "check_interval": self.interval_spinbox.value(),
                "subject_filter": self.subject_filter_edit.text(),
                "sender_filter": self.sender_filter_edit.text()
            })
        
        elif self.trigger_type == "schedule":
            schedule_type = self.schedule_type_combo.currentText()
            data["schedule_type"] = schedule_type
            
            if schedule_type == "间隔":
                data["interval"] = self.interval_schedule_spinbox.value()
            
            elif schedule_type == "每天":
                data.update({
                    "hour": self.daily_hour_spinbox.value(),
                    "minute": self.daily_minute_spinbox.value()
                })
            
            elif schedule_type == "每周":
                data.update({
                    "day": self.day_combo.currentText(),
                    "hour": self.weekly_hour_spinbox.value(),
                    "minute": self.weekly_minute_spinbox.value()
                })
            
            elif schedule_type == "每月":
                data.update({
                    "day_of_month": self.day_of_month_spinbox.value(),
                    "hour": self.monthly_hour_spinbox.value(),
                    "minute": self.monthly_minute_spinbox.value()
                })
            
            elif schedule_type == "Cron表达式":
                data["cron"] = self.cron_edit.text()
        
        return data


class TriggersPage(QWidget):
    """触发器管理页面"""
    
    def __init__(self, config, database, task_scheduler):
        super().__init__()
        self.config = config
        self.database = database
        self.task_scheduler = task_scheduler
        self.triggers = []  # 触发器列表
        self._setup_ui()
        self._load_triggers()
        logging.info("触发器管理页面已初始化")
    
    def _setup_ui(self):
        """设置UI"""
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(20, 20, 20, 20)
        
        # 标题
        title_label = QLabel("触发器管理")
        title_label.setStyleSheet("font-size: 24px; font-weight: bold;")
        main_layout.addWidget(title_label)
        
        # 触发器类型标签页
        self.tabs = QTabWidget()
        
        # 文件触发器
        self.file_tab = QWidget()
        self._setup_trigger_tab(self.file_tab, "file", "文件触发器")
        self.tabs.addTab(self.file_tab, "文件触发器")
        
        # Webhook触发器
        self.webhook_tab = QWidget()
        self._setup_trigger_tab(self.webhook_tab, "webhook", "Webhook触发器")
        self.tabs.addTab(self.webhook_tab, "Webhook触发器")
        
        # 邮件触发器
        self.email_tab = QWidget()
        self._setup_trigger_tab(self.email_tab, "email", "邮件触发器")
        self.tabs.addTab(self.email_tab, "邮件触发器")
        
        # 定时触发器
        self.schedule_tab = QWidget()
        self._setup_trigger_tab(self.schedule_tab, "schedule", "定时触发器")
        self.tabs.addTab(self.schedule_tab, "定时触发器")
        
        main_layout.addWidget(self.tabs)
    
    def _setup_trigger_tab(self, tab, trigger_type, title):
        """设置触发器标签页"""
        layout = QVBoxLayout(tab)
        
        # 工具栏
        toolbar_layout = QHBoxLayout()
        
        # 新建触发器按钮
        new_trigger_btn = QPushButton(f"新建{title.split('触发器')[0]}触发器")
        new_trigger_btn.clicked.connect(lambda: self._create_trigger(trigger_type))
        toolbar_layout.addWidget(new_trigger_btn)
        
        toolbar_layout.addStretch()
        
        # 搜索框
        toolbar_layout.addWidget(QLabel("搜索:"))
        search_edit = QLineEdit()
        search_edit.setPlaceholderText("输入关键字搜索触发器")
        search_edit.textChanged.connect(lambda text: self._filter_triggers(trigger_type, text))
        toolbar_layout.addWidget(search_edit)
        
        layout.addLayout(toolbar_layout)
        
        # 触发器表格
        table = QTableWidget()
        table.setColumnCount(4)
        table.setHorizontalHeaderLabels(["名称", "描述", "状态", "脚本"])
        table.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeMode.Stretch)
        table.horizontalHeader().setSectionResizeMode(1, QHeaderView.ResizeMode.Stretch)
        table.horizontalHeader().setSectionResizeMode(2, QHeaderView.ResizeMode.ResizeToContents)
        table.horizontalHeader().setSectionResizeMode(3, QHeaderView.ResizeMode.Stretch)
        table.setSelectionBehavior(QTableWidget.SelectionBehavior.SelectRows)
        table.setSelectionMode(QTableWidget.SelectionMode.SingleSelection)
        table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
        table.itemDoubleClicked.connect(lambda item: self._edit_trigger(trigger_type))
        table.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
        table.customContextMenuRequested.connect(lambda pos: self._show_context_menu(trigger_type, pos))
        
        # 保存表格引用
        setattr(self, f"{trigger_type}_table", table)
        
        layout.addWidget(table)
    
    def _load_triggers(self):
        """加载触发器列表"""
        # 这里应该从数据库加载触发器列表
        # 目前使用模拟数据
        self.triggers = [
            {
                "id": 1,
                "name": "新文件监控",
                "description": "监控下载目录中的新文件",
                "type": "file",
                "enabled": True,
                "directory": "C:/Downloads",
                "pattern": "*.xlsx",
                "recursive": False,
                "events": ["created"],
                "script": "网页爬虫示例"
            },
            {
                "id": 2,
                "name": "数据接收接口",
                "description": "接收外部系统推送的数据",
                "type": "webhook",
                "enabled": True,
                "port": 8000,
                "path": "/api/data",
                "method": "POST",
                "auth_required": False,
                "script": "桌面自动化示例"
            },
            {
                "id": 3,
                "name": "每日报表",
                "description": "每天早上8点生成报表",
                "type": "schedule",
                "enabled": True,
                "schedule_type": "每天",
                "hour": 8,
                "minute": 0,
                "script": "网页爬虫示例"
            },
            {
                "id": 4,
                "name": "邮件通知处理",
                "description": "处理特定邮件通知",
                "type": "email",
                "enabled": False,
                "server": "imap.example.com",
                "port": 993,
                "username": "user@example.com",
                "password": "password",
                "check_interval": 300,
                "subject_filter": "通知|提醒|警告",
                "sender_filter": "system@example.com",
                "script": "桌面自动化示例"
            },
        ]
        
        self._update_trigger_tables()
    
    def _update_trigger_tables(self):
        """更新触发器表格"""
        # 清空表格
        for trigger_type in ["file", "webhook", "email", "schedule"]:
            table = getattr(self, f"{trigger_type}_table")
            table.setRowCount(0)
        
        # 填充表格
        for trigger in self.triggers:
            trigger_type = trigger["type"]
            table = getattr(self, f"{trigger_type}_table")
            
            row = table.rowCount()
            table.insertRow(row)
            
            table.setItem(row, 0, QTableWidgetItem(trigger["name"]))
            table.setItem(row, 1, QTableWidgetItem(trigger["description"]))
            
            status_item = QTableWidgetItem("启用" if trigger["enabled"] else "禁用")
            status_item.setForeground(QColor("#2ecc71" if trigger["enabled"] else "#e74c3c"))
            table.setItem(row, 2, status_item)
            
            table.setItem(row, 3, QTableWidgetItem(trigger["script"]))
        
        # 为每个表格添加上下文菜单
        for trigger_type in ["file", "webhook", "email", "schedule"]:
            table = getattr(self, f"{trigger_type}_table")
            table.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
            table.customContextMenuRequested.connect(lambda pos, t=trigger_type: self._show_context_menu(t, pos))
    
    def _filter_triggers(self, trigger_type, text):
        """筛选触发器列表"""
        table = getattr(self, f"{trigger_type}_table")
        table.setRowCount(0)
        
        search_text = text.lower()
        
        for trigger in self.triggers:
            if trigger["type"] != trigger_type:
                continue
                
            if search_text and search_text not in trigger["name"].lower() and search_text not in trigger["description"].lower():
                continue
            
            row = table.rowCount()
            table.insertRow(row)
            
            table.setItem(row, 0, QTableWidgetItem(trigger["name"]))
            table.setItem(row, 1, QTableWidgetItem(trigger["description"]))
            
            status_item = QTableWidgetItem("启用" if trigger["enabled"] else "禁用")
            status_item.setForeground(QColor("#2ecc71" if trigger["enabled"] else "#e74c3c"))
            table.setItem(row, 2, status_item)
            
            table.setItem(row, 3, QTableWidgetItem(trigger["script"]))
    
    def _show_context_menu(self, trigger_type, position):
        """显示上下文菜单"""
        table = getattr(self, f"{trigger_type}_table")
        current_row = table.currentRow()
        
        if current_row >= 0:
            menu = QMenu()
            
            edit_action = QAction("编辑触发器", self)
            edit_action.triggered.connect(lambda: self._edit_trigger(trigger_type))
            menu.addAction(edit_action)
            
            # 获取当前触发器
            trigger = None
            for t in self.triggers:
                if t["type"] == trigger_type and t["name"] == table.item(current_row, 0).text():
                    trigger = t
                    break
            
            if trigger:
                if trigger["enabled"]:
                    disable_action = QAction("禁用触发器", self)
                    disable_action.triggered.connect(lambda: self._toggle_trigger(trigger, False))
                    menu.addAction(disable_action)
                else:
                    enable_action = QAction("启用触发器", self)
                    enable_action.triggered.connect(lambda: self._toggle_trigger(trigger, True))
                    menu.addAction(enable_action)
            
            delete_action = QAction("删除触发器", self)
            delete_action.triggered.connect(lambda: self._delete_trigger(trigger_type))
            menu.addAction(delete_action)
            
            # 跳转到脚本
            script_name = table.item(current_row, 3).text()
            goto_script_action = QAction(f"跳转到脚本: {script_name}", self)
            goto_script_action.triggered.connect(lambda: self._goto_script(script_name))
            menu.addAction(goto_script_action)
            
            menu.exec(table.mapToGlobal(position))
    
    def _goto_script(self, script_name):
        """跳转到脚本页面"""
        # 切换到脚本页面
        main_window = self.window()
        main_window.tabs.setCurrentIndex(2)  # 脚本页面的索引
        logging.info(f"跳转到脚本: {script_name}")
    
    def _create_trigger(self, trigger_type):
        """创建新触发器"""
        dialog = TriggerDialog(trigger_type, parent=self)
        if dialog.exec():
            trigger_data = dialog.get_trigger_data()
            trigger_data["id"] = len(self.triggers) + 1  # 简单生成ID
            self.triggers.append(trigger_data)
            self._update_trigger_tables()
            logging.info(f"已创建{dialog._get_type_name()}触发器: {trigger_data['name']}")
    
    def _edit_trigger(self, trigger_type):
        """编辑触发器"""
        table = getattr(self, f"{trigger_type}_table")
        current_row = table.currentRow()
        
        if current_row >= 0:
            trigger_name = table.item(current_row, 0).text()
            
            # 查找对应的触发器
            trigger = None
            for t in self.triggers:
                if t["type"] == trigger_type and t["name"] == trigger_name:
                    trigger = t
                    break
            
            if trigger:
                dialog = TriggerDialog(trigger_type, trigger, parent=self)
                if dialog.exec():
                    updated_data = dialog.get_trigger_data()
                    # 更新触发器数据，保留ID
                    trigger.update(updated_data)
                    self._update_trigger_tables()
                    logging.info(f"已更新{dialog._get_type_name()}触发器: {trigger['name']}")
    
    def _delete_trigger(self, trigger_type):
        """删除触发器"""
        table = getattr(self, f"{trigger_type}_table")
        current_row = table.currentRow()
        
        if current_row >= 0:
            trigger_name = table.item(current_row, 0).text()
            
            # 查找对应的触发器
            trigger_index = -1
            for i, t in enumerate(self.triggers):
                if t["type"] == trigger_type and t["name"] == trigger_name:
                    trigger_index = i
                    break
            
            if trigger_index >= 0:
                trigger = self.triggers[trigger_index]
                reply = QMessageBox.question(
                    self, "确认删除", f"确定要删除触发器 '{trigger['name']}' 吗？",
                    QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
                    QMessageBox.StandardButton.No
                )
                
                if reply == QMessageBox.StandardButton.Yes:
                    del self.triggers[trigger_index]
                    self._update_trigger_tables()
                    logging.info(f"已删除触发器: {trigger['name']}")
    
    def _toggle_trigger(self, trigger, enabled):
        """切换触发器启用状态"""
        trigger["enabled"] = enabled
        self._update_trigger_tables()
        status = "启用" if enabled else "禁用"
        logging.info(f"已{status}触发器: {trigger['name']}")